/**
 * Copyright: Copyright (c) 2012
 * Company:anhosi.com
 * @author lifuyu
 * @date Aug 12, 2012
 * @version V1.0
 *
 * @Description: 
 */
package com.microcm.insync.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.microcm.common.BeanUtils;
import com.microcm.common.CUtils;
import com.microcm.common.Final;
import com.microcm.common.SystemToolkit;
import com.microcm.insync.service.InsyncService;
import com.microcmframework.core.entity.PageBean;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.ItemCat;
import com.taobao.api.domain.Shop;
import com.taobao.api.domain.TaobaokeItem;
import com.taobao.api.domain.TaobaokeShop;
import com.taobao.api.request.ItemcatsGetRequest;
import com.taobao.api.request.ShopGetRequest;
import com.taobao.api.request.TaobaokeItemsConvertRequest;
import com.taobao.api.request.TaobaokeItemsGetRequest;
import com.taobao.api.request.TaobaokeListurlGetRequest;
import com.taobao.api.request.TaobaokeShopsConvertRequest;
import com.taobao.api.response.ItemcatsGetResponse;
import com.taobao.api.response.ShopGetResponse;
import com.taobao.api.response.TaobaokeItemsConvertResponse;
import com.taobao.api.response.TaobaokeItemsGetResponse;
import com.taobao.api.response.TaobaokeListurlGetResponse;
import com.taobao.api.response.TaobaokeShopsConvertResponse;

/**
 * @author kansum
 * 
 */
@Service("insyncService")
public class InsyncServiceImpl implements InsyncService
{
	private Logger logger = LoggerFactory.getLogger(InsyncServiceImpl.class.getName());

	private String apiUrl;

	private String appKey;

	private String appSecret;

	private String nick;

	public InsyncServiceImpl()
	{
		this.apiUrl = SystemToolkit.getSystemConfigValue(Final.TAOBAO_API_INVOKE_URL, null);
		this.appKey = SystemToolkit.getSystemConfigValue(Final.TAOBAO_API_APP_KEY, null);
		this.appSecret = SystemToolkit.getSystemConfigValue(Final.TAOBAO_API_APP_SECRET, null);
		// this.nick = SystemToolkit.getSystemConfigValue(Final.TAOBAO_NICK,
		// null);

		if (apiUrl == null || appKey == null || appSecret == null)
		{
			logger.error("apiUrl/appKey/appSecret not configuration!");
		}
	}

	/**
	 * 同步淘宝商品分类数据
	 * 
	 * @author：lifuyu
	 * 
	 * @return
	 */
	public String categorySynchronizingFromTaobao(long parentCid, List<Map<String, Object>> resultList)
	{
		TaobaoClient client = new DefaultTaobaoClient(apiUrl, appKey, appSecret);
		ItemcatsGetRequest req = new ItemcatsGetRequest();
		req.setFields("cid,parent_cid,name,is_parent,sort_order");
		req.setParentCid(parentCid);
		List<ItemCat> apiRetList;
		try
		{
			ItemcatsGetResponse resp = client.execute(req);
			apiRetList = resp.getItemCats();
		}
		catch (ApiException e)
		{
			logger.error(e.getMessage(), e);
			return e.getErrMsg() == null ? e.getMessage() : e.getErrMsg();
		}

		if (CUtils.isEmpty(apiRetList))
			return "0";

		for (ItemCat cat : apiRetList)
		{
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("id", CUtils.toStr(cat.getCid()));
			m.put("text", cat.getName());
			if (cat.getIsParent())
				m.put("state", "closed");
			else
				m.put("state", "open");

			Map<String, Object> attrM = new HashMap<String, Object>();
			attrM.put("isParent", cat.getIsParent());
			attrM.put("parentCid", cat.getParentCid());
			attrM.put("sortOrder", cat.getSortOrder());
			m.put("attributes", attrM);
			resultList.add(m);
		}
		return "1";
	}

	/**
	 * 同步淘宝商品数据
	 * 
	 * @author：lifuyu
	 * 
	 * @return
	 */
	public String goodsSynchronizingFromTaobao(Long cid, String sort, PageBean pageBean)
	{
		TaobaoClient client = new DefaultTaobaoClient(apiUrl, appKey, appSecret, "json", 5000, 30000);
		TaobaokeItemsGetRequest req = new TaobaokeItemsGetRequest();
		req.setFields("num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume");
		if (this.nick != null)
			req.setNick(this.nick);
		req.setCid(cid);
		if (CUtils.isNotEmpty(pageBean.getSearchString()))
		{
			req.setKeyword(pageBean.getSearchString());
		}
		if (CUtils.isNotEmpty(sort))
		{
			req.setSort(sort);
		}
		req.setOuterCode(Final.UNID_DEFAULT);
		req.setPageSize(Integer.valueOf(pageBean.getPageSize()).longValue());
		req.setPageNo(Integer.valueOf(pageBean.getPage()).longValue());

		Long totalRecord = 0L;
		List<TaobaokeItem> apiRetList;
		try
		{
			TaobaokeItemsGetResponse resp = client.execute(req);
			apiRetList = resp.getTaobaokeItems();
			totalRecord = resp.getTotalResults();
		}
		catch (ApiException e)
		{
			logger.error(e.getMessage(), e);
			return e.getErrMsg() == null ? e.getMessage() : e.getErrMsg();
		}
		if (CUtils.isEmpty(apiRetList))
			return "0";

		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		for (TaobaokeItem item : apiRetList)
		{
			try
			{
				Map<String, Object> m = BeanUtils.describe(item);
				resultList.add(m);
			}
			catch (Exception e)
			{
				logger.error(e.getMessage(), e);
				e.printStackTrace();
			}
		}
		pageBean.setRoot(resultList);
		pageBean.setTotalRecord(totalRecord.intValue());
		pageBean.setTotalPage((pageBean.getTotalRecord() + pageBean.getPageSize() - 1) / pageBean.getPageSize());

		return "1";
	}

	/**
	 * 通过关键词查询，获得s8的url
	 * 
	 * @author：lifuyu
	 * 
	 * @return
	 */
	public String getS8UrlFromTaobao(String unid, String keyword)
	{
		if (CUtils.isEmpty(unid))
			unid = Final.UNID_DEFAULT;

		TaobaoClient client = new DefaultTaobaoClient(apiUrl, appKey, appSecret);
		TaobaokeListurlGetRequest req = new TaobaokeListurlGetRequest();
		if (this.nick != null)
			req.setNick(this.nick);
		req.setOuterCode(unid);
		req.setQ(keyword);

		TaobaokeItem taobaokeItem;
		try
		{
			TaobaokeListurlGetResponse resp = client.execute(req);
			taobaokeItem = resp.getTaobaokeItem();
		}
		catch (ApiException e)
		{
			logger.error(e.getMessage(), e);
			return e.getErrMsg() == null ? e.getMessage() : e.getErrMsg();
		}
		if (taobaokeItem == null)
			return null;

		return taobaokeItem.getKeywordClickUrl();
	}

	/**
	 * 通过商品numiid查询，获得转换后的商品
	 * 
	 * @author：lifuyu
	 * 
	 * @return
	 */
	public String getConvertGoodsFromTaobao(String unid, String numIids, PageBean pageBean)
	{
		if (CUtils.isEmpty(unid))
			unid = Final.UNID_DEFAULT;

		TaobaoClient client = new DefaultTaobaoClient(apiUrl, appKey, appSecret);
		TaobaokeItemsConvertRequest req = new TaobaokeItemsConvertRequest();
		req.setNumIids(numIids);
		if (this.nick != null)
			req.setNick(this.nick);
		req.setOuterCode(unid);
		req.setFields("num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume");

		Long totalRecord = 0L;
		List<TaobaokeItem> apiRetList;
		try
		{
			TaobaokeItemsConvertResponse resp = client.execute(req);
			apiRetList = resp.getTaobaokeItems();
			totalRecord = resp.getTotalResults();
		}
		catch (ApiException e)
		{
			logger.error(e.getMessage(), e);
			return e.getErrMsg() == null ? e.getMessage() : e.getErrMsg();
		}
		if (CUtils.isEmpty(apiRetList))
			return "0";

		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		for (TaobaokeItem item : apiRetList)
		{
			try
			{
				Map<String, Object> m = BeanUtils.describe(item);
				resultList.add(m);
			}
			catch (Exception e)
			{
				logger.error(e.getMessage(), e);
				e.printStackTrace();
			}
		}
		pageBean.setRoot(resultList);
		pageBean.setTotalRecord(totalRecord.intValue());
		return "1";
	}

	/**
	 * 根据昵称获得店铺
	 * 
	 * @author kansum
	 */
	public Shop getShopFromTaobao(String nick)
	{
		TaobaoClient client = new DefaultTaobaoClient(apiUrl, appKey, appSecret);
		ShopGetRequest req = new ShopGetRequest();
		req.setNick(nick);
		req.setFields("sid,cid,nick,title,desc,pic_path,created,modified,shop_score");

		Shop shop = null;
		try
		{
			ShopGetResponse resp = client.execute(req);
			shop = resp.getShop();
		}
		catch (ApiException e)
		{
			logger.error(e.getMessage(), e);
		}
		return shop;
	}

	/**
	 * 通过店铺sid串查询，获得转换后的店铺
	 * 
	 * @author：lifuyu
	 * 
	 * @return
	 */
	public String getConvertShopsFromTaobao(String unid, String sids, PageBean pageBean)
	{
		if (CUtils.isEmpty(unid))
			unid = Final.UNID_DEFAULT;

		TaobaoClient client = new DefaultTaobaoClient(apiUrl, appKey, appSecret);
		TaobaokeShopsConvertRequest req = new TaobaokeShopsConvertRequest();
		req.setSids(sids);
		if (this.nick != null)
			req.setNick(this.nick);
		req.setOuterCode(unid);
		req.setFields("user_id,shop_title,click_url,commission_rate");

		List<TaobaokeShop> apiRetList;
		try
		{
			TaobaokeShopsConvertResponse resp = client.execute(req);
			apiRetList = resp.getTaobaokeShops();
		}
		catch (ApiException e)
		{
			logger.error(e.getMessage(), e);
			return e.getErrMsg() == null ? e.getMessage() : e.getErrMsg();
		}
		if (CUtils.isEmpty(apiRetList))
			return "0";

		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		for (TaobaokeShop item : apiRetList)
		{
			try
			{
				Map<String, Object> m = BeanUtils.describe(item);
				resultList.add(m);
			}
			catch (Exception e)
			{
				logger.error(e.getMessage(), e);
				e.printStackTrace();
			}
		}
		pageBean.setRoot(resultList);
		pageBean.setTotalRecord(apiRetList.size());
		return "1";
	}
}
